Page({
  data: {
    fileNames: [], // 用于存储照片目录的数组
    autoRefreshInterval: null, // 用于存储自动刷新的定时器
    loading: false, // 加载状态
    deviceStatus: '离线', // 设备状态，默认为离线
    deviceStatusColor: '#FF0000', // 设备状态颜色，默认为红色
    voltage: 0, // 电压值，默认为 0
  },

  onLoad: function() {
    this.fetchDeviceStatus(); // 获取设备状态
    this.fetchFileList();
    this.startAutoRefresh(); // 启动自动刷新
  },

  // 获取设备状态
  fetchDeviceStatus() {
    const url = 'https://iot-api.heclouds.com/device/detail';
    const params = {
      product_id: '35ow3L3sv7',
      device_name: 'iot_camera'
    };
    const authHeader = 'version=2022-05-01&res=userid%2F433704&et=1838393020&method=sha1&sign=k9xbaMQ5MgUvbMhJMjRzY8YU9No%3D';

    const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
    const fullUrl = `${url}?${queryString}`;

    wx.request({
      url: fullUrl,
      method: 'GET',
      header: {
        'Authorization': authHeader
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const deviceStatus = res.data.data.status;
          console.log("设备状态：" + deviceStatus);
          let statusText = '离线';
          let statusColor = '#FF0000';
          if (deviceStatus === 1) {
            statusText = '在线';
            statusColor = '#00FF00'; // 在线状态为绿色
          } else if (deviceStatus === 2) {
            statusText = '未激活';
            statusColor = '#FFA500'; // 未激活状态为橙色
          }
          this.setData({
            deviceStatus: statusText,
            deviceStatusColor: statusColor
          });
        } else {
          wx.showToast({
            title: `获取设备状态失败，状态码：${res.statusCode}，消息：${res.data.msg}`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取设备状态失败:', err.errMsg);
        wx.showToast({
          title: `获取设备状态失败，错误信息：${err.errMsg}`,
          icon: 'none'
        });
      }
    });
  },

  fetchFileList() {
    this.setData({ loading: true });
    const url = 'https://iot-api.heclouds.com/datapoint/history-datapoints';
    const params = {
      product_id: '35ow3L3sv7',
      device_name: 'iot_camera',
      datastream_id: 'fileDir,power' // 新增 power 数据流
    };
    const authHeader = 'version=2022-05-01&res=userid%2F433704&et=1838393020&method=sha1&sign=k9xbaMQ5MgUvbMhJMjRzY8YU9No%3D';

    const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
    const fullUrl = `${url}?${queryString}`;

    wx.request({
      url: fullUrl,
      method: 'GET',
      header: {
        'Authorization': authHeader
      },
      success: (res) => {
        console.log(res.data);
        this.setData({ loading: false });
        if (res.statusCode === 200 && res.data.code === 0) {
          const datastreams = res.data.data.datastreams;
          let fileNames = [];
          let batteryLow = false;
          let voltage = 0; // 默认电压值为 0

          // 处理 fileDir 数据流
          const fileDirDatastream = datastreams.find(ds => ds.id === 'fileDir');
          if (fileDirDatastream && fileDirDatastream.datapoints && fileDirDatastream.datapoints.length > 0) {
            fileNames = fileDirDatastream.datapoints[0].value.split(","); // 使用逗号分隔字符串，得到文件名数组
          }

          // 处理 power 数据流
          const powerDatastream = datastreams.find(ds => ds.id === 'power');
          if (powerDatastream && powerDatastream.datapoints && powerDatastream.datapoints.length > 0) {
            voltage = parseFloat(powerDatastream.datapoints[0].value).toFixed(2); // 获取电压值并保留两位小数
          }

          this.setData({
            fileNames: fileNames,
            voltage: voltage // 更新电压值
          });
        } else {
          wx.showToast({
            title: `请求失败，状态码：${res.statusCode}，消息：${res.data.msg}`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        this.setData({ loading: false });
        console.error('请求失败的错误信息:', err.errMsg); // 打印请求失败的错误信息
        this.setData({
          fileNames: [], // 请求失败，清空文件名数组
          batteryLow: false, // 请求失败，重置电量状态
          voltage: 0 // 请求失败，重置电压值
        });
        wx.showToast({
          title: `请求失败，错误信息：${err.errMsg}`,
          icon: 'none'
        });
      }
    });
  },

  startAutoRefresh: function() {
    const interval = 3000; // 自动刷新的间隔时间（毫秒），这里设置为3秒
    this.setData({
      autoRefreshInterval: setInterval(() => {
        this.fetchFileList(); // 每隔指定时间调用 fetchFileList 方法刷新文件列表
        this.fetchDeviceStatus(); // 每隔指定时间刷新设备状态
      }, interval)
    });
  },

  onUnload: function() {
    // 页面卸载时停止自动刷新
    const interval = this.data.autoRefreshInterval;
    if (interval) {
      clearInterval(interval);
      this.setData({
        autoRefreshInterval: null
      });
    }
  },

  onFileClick: function(event) {
    const fileName = event.currentTarget.dataset.filename; // 获取点击的文件名
    // 跳转到另一个页面，并传递文件名
    wx.navigateTo({
      url: `/pages/image-parser/image-parser?filename=${encodeURIComponent(fileName)}`
    });

    // 发送图片更新指令
    this.sendCommand(fileName);
  },

  sendCommand(fileName) {
    const url = 'https://iot-api.heclouds.com/datapoint/synccmds';
    const authHeader = 'version=2022-05-01&res=userid%2F433704&et=1838393020&method=sha1&sign=k9xbaMQ5MgUvbMhJMjRzY8YU9No%3D';
    const product_id = '35ow3L3sv7';
    const device_name = 'iot_camera';
    const timeout = '5'; // 超时时间，单位秒
    const command = `${fileName}`; // 命令字符串

    const queryString = `product_id=${encodeURIComponent(product_id)}&device_name=${encodeURIComponent(device_name)}&timeout=${encodeURIComponent(timeout)}`;
    const fullUrl = `${url}?${queryString}`;

    wx.request({
      url: fullUrl,
      method: 'POST',
      header: {
        'Authorization': authHeader,
        'Content-Type': 'application/json'
      },
      data: command, // 直接发送命令字符串
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({
            title: '指令发送成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: `指令发送失败，状态码：${res.statusCode}，消息：${res.data.msg}`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败的错误信息:', err.errMsg); // 打印请求失败的错误信息
        wx.showToast({
          title: `指令发送失败，错误信息：${err.errMsg}`,
          icon: 'none'
        });
      }
    });
  },

  sendClearCommand: function() {
    const url = 'https://iot-api.heclouds.com/datapoint/synccmds';
    const authHeader = 'version=2022-05-01&res=userid%2F433704&et=1838393020&method=sha1&sign=k9xbaMQ5MgUvbMhJMjRzY8YU9No%3D';
    const product_id = '35ow3L3sv7';
    const device_name = 'iot_camera';
    const timeout = '5'; // 超时时间，单位秒
    const command = 'JPGclear'; // 下发的“clear”指令

    const queryString = `product_id=${encodeURIComponent(product_id)}&device_name=${encodeURIComponent(device_name)}&timeout=${encodeURIComponent(timeout)}`;
    const fullUrl = `${url}?${queryString}`;

    wx.request({
      url: fullUrl,
      method: 'POST',
      header: {
        'Authorization': authHeader,
        'Content-Type': 'application/json'
      },
      data: command, // 直接发送“clear”指令
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({
            title: 'Clear 指令发送成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: `Clear 指令发送失败，状态码：${res.statusCode}，消息：${res.data.msg}`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败的错误信息:', err.errMsg); // 打印请求失败的错误信息
        wx.showToast({
          title: `Clear 指令发送失败，错误信息：${err.errMsg}`,
          icon: 'none'
        });
      }
    });
  }
});